package com.lm.ffmpeg.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class FFmpegUtil {

    /**
     * 执行 FFmpeg 命令
     * @param command FFmpeg 命令字符串
     * @throws Exception
     */
    public static void executeCommand(String command) throws Exception {
        ProcessBuilder builder = new ProcessBuilder(command.split(" "));
        builder.redirectErrorStream(true);
        Process process = builder.start();

        // 输出日志
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("[FFmpeg] " + line);
            }
        }

        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("FFmpeg 执行失败，退出码：" + exitCode);
        }
    }

    /**
     * 转换指定目录下的所有视频文件（不递归子目录）
     * @param inputDir   输入目录
     * @param outputDir  输出目录
     * @param targetFormat 输出格式（如 mp4、avi、mov）
     */
    public static void convertFilesInDirectory(String inputDir, String outputDir, String targetFormat) throws Exception {
        File inDir = new File(inputDir);
        if (!inDir.exists() || !inDir.isDirectory()) {
            throw new IllegalArgumentException("输入目录不存在: " + inputDir);
        }

        File outDir = new File(outputDir);
        if (!outDir.exists()) {
            outDir.mkdirs();
        }

        // 只过滤视频文件（这里简单用扩展名判断）
        File[] files = inDir.listFiles((dir, name) ->
                name.toLowerCase().endsWith(".mp4") ||
                        name.toLowerCase().endsWith(".avi") ||
                        name.toLowerCase().endsWith(".mov") ||
                        name.toLowerCase().endsWith(".mkv")
        );

        if (files == null || files.length == 0) {
            System.out.println("目录下没有可转换的视频文件。");
            return;
        }

        for (File file : files) {
            String inputPath = file.getAbsolutePath();
            String outputPath = new File(outDir,
                    file.getName().replaceFirst("\\.[^.]+$", "") + "." + targetFormat
            ).getAbsolutePath();

            String cmd = String.format("ffmpeg -i %s %s", inputPath, outputPath);
            System.out.println("开始转换：" + inputPath + " -> " + outputPath);
            executeCommand(cmd);
        }
    }
}
